package com.helen.ui.applymerchent;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.coorchice.library.SuperTextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.helen.db.UserHelper;
import com.helen.global.Constants;
import com.helen.shopping.R;
import com.helen.ui.BaseActivity;
import com.helen.ui.applymerchent.entity.AddNewRecoveryEntity;
import com.helen.utils.ImageLoadUtil;
import com.helen.utils.JsonUtil;
import com.helen.utils.MyLog;
import com.helen.utils.PhoneUtils;
import com.helen.utils.PhotoSelectUtils;
import com.helen.utils.tiputils.MToast;
import com.helen.widget.ActionSheetDialog;
import com.helen.widget.MyEditText;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by yang on 2019/5/21
 */
public class ApplyMerchantActivity extends BaseActivity {
    @BindView(R.id.img_zm)
    ImageView imgZm;
    @BindView(R.id.img_fm)
    ImageView imgFm;
    @BindView(R.id.et_name)
    MyEditText etName;
    @BindView(R.id.et_phone)
    MyEditText etPhone;
    @BindView(R.id.et_id_card)
    MyEditText etIdCard;
    @BindView(R.id.rb_p)
    RadioButton rbP;
    @BindView(R.id.rb_c)
    RadioButton rbC;
    @BindView(R.id.rb_a)
    RadioButton rbA;
    @BindView(R.id.radiogroup)
    RadioGroup radiogroup;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.ll_select_location)
    LinearLayout llSelectLocation;
    @BindView(R.id.tv_create)
    SuperTextView tvCreate;
    private String img1;
    private String img2;
    private PhotoSelectUtils photoSelectUtils = new PhotoSelectUtils(ApplyMerchantActivity.this);
    private List<LocalMedia> selectList = new ArrayList<>();
    private int imgType = 1;
    private int selectLocation = 1;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_apply_merchant;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText("代理申请");
        initImgParams();
        AgentCityListApi();
    }

    @Override
    protected void updateViews() {

    }

    private void initImgParams() {
        photoSelectUtils.setCircleDimmedLayer(false);
        photoSelectUtils.setImgWidthProportion(4);
        photoSelectUtils.setImgHightProportion(3);
        photoSelectUtils.setShowCropFrame(true);
        photoSelectUtils.setShowCropGrid(true);
    }


    @OnClick({R.id.img_zm, R.id.img_fm, R.id.rb_p, R.id.rb_c, R.id.rb_a, R.id.ll_select_location, R.id.tv_create})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_zm:
                imgType = 1;
                selectPhoto();
                break;
            case R.id.img_fm:
                imgType = 2;
                selectPhoto();
                break;
            case R.id.rb_p:
                selectLocation = 1;
                tvLocation.setHint("请选择代理地区");
                cityId = 0;
                break;
            case R.id.rb_c:
                selectLocation = 2;
                tvLocation.setHint("请选择代理地区");
                cityId = 0;
                break;
            case R.id.rb_a:
                selectLocation = 3;
                tvLocation.setHint("请选择代理地区");
                cityId = 0;
                break;
            case R.id.ll_select_location:
                showPicker(selectLocation);
                break;
            case R.id.tv_create:
                if (TextUtils.isEmpty(img1)) {
                    MToast.makeTextShort(ApplyMerchantActivity.this, "请添加身份证正面").show();
                    return;
                }
                if (TextUtils.isEmpty(img2)) {
                    MToast.makeTextShort(ApplyMerchantActivity.this, "请添加身份证反面").show();
                    return;
                }

                String name = etName.getText().toString();
                String phone = etPhone.getText().toString();
                String idCard = etIdCard.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    MToast.makeTextShort(ApplyMerchantActivity.this, "请输入姓名").show();
                    etName.requestFocus();
                    return;
                }

                if (TextUtils.isEmpty(phone)) {
                    MToast.makeTextShort(ApplyMerchantActivity.this, "请输入手机号码").show();
                    etPhone.requestFocus();
                    return;
                }
                if (TextUtils.isEmpty(idCard)) {
                    MToast.makeTextShort(ApplyMerchantActivity.this, "请输入身份证号码").show();
                    etIdCard.requestFocus();
                    return;
                }

                if (cityId == 0) {
                    MToast.makeTextShort(ApplyMerchantActivity.this, "请选择代理级别").show();
                    return;
                }
                applyAgentApi(name, phone, idCard);

                break;
        }
    }

    private void applyAgentApi(String name, String phone, String idCard) {
        mMProgressDialog.show();
        HttpParams params = new HttpParams();
        params.put("userId", UserHelper.getInstance().getloginEntity(ApplyMerchantActivity.this).getId() + "");
        params.put("phone", phone);
        params.put("name", name);
        params.put("idCard", idCard);
        params.put("cityId", cityId + "");
        params.put("idCardImgZ", img1);
        params.put("idCardImgF", img2);
        EasyHttp.post(Constants.APPLYAGENT)
                .baseUrl(Constants.APP_API_BASE2)
                .params(params)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onSuccess(String s) {
                        mMProgressDialog.dismiss();
                        String data = PhoneUtils.checkResponseFlag(ApplyMerchantActivity.this, s, TAG);
                        if (data != null) {
                            startActivity(new Intent(ApplyMerchantActivity.this,CheckApplyActivity.class).putExtra("type","正在为您审核，请稍后…"));
                            finish();
                        }
                    }
                });
    }


    private void selectPhoto() {
        new ActionSheetDialog(ApplyMerchantActivity.this).builder()
                .setCancelable(false)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("拍照", ActionSheetDialog.SheetItemColor.ThemeColor,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                photoSelectUtils.showCameraAction();
                            }
                        })
                .addSheetItem("相册", ActionSheetDialog.SheetItemColor.ThemeColor,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                selectList.clear();
                                photoSelectUtils.pickImageAction(selectList);
                            }
                        }).show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    mMProgressDialog.show();
                    // 图片返回
                    selectList.clear();
                    selectList = PictureSelector.obtainMultipleResult(data);
                    String path = selectList.get(0).getCompressPath();
                    if (imgType == 1) {
                        ImageLoadUtil.displayImage(this, imgZm, path, R.mipmap.app_logo, R.mipmap.app_logo);
                    }
                    if (imgType == 2) {
                        ImageLoadUtil.displayImage(this, imgFm, path, R.mipmap.app_logo, R.mipmap.app_logo);
                    }
                    uploadImg(path);

                    break;

            }
        }
    }


    //上传快递照片
    private void uploadImg(String imgPath) {
        mMProgressDialog.show();
        final String url = Constants.APP_API_BASE2 + Constants.UPDATEIMG;
        RequestParams params = new RequestParams(url);
        params.setMultipart(true);
        try {
            params.addBodyParameter("file", new FileInputStream(new File(imgPath)), "img/jpg", getPhotoFileName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "上传图片成功==" + result);
                mMProgressDialog.dismiss();
                int code = JsonUtil.getJsonValuesInt(result, "code");
                String msg = JsonUtil.getJsonValuesString(result, "msg");
                if (code == 0) {
                    String urls = JsonUtil.getJsonValuesString(result, "urls");
                    switch (imgType) {
                        case 1:
                            img1 = urls;
                            break;
                        case 2:
                            img2 = urls;
                            break;
                    }
                } else {
                    MToast.makeTextShort(ApplyMerchantActivity.this, msg).show();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang", "上传图片失败=" + ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mMProgressDialog.dismiss();
            }
        });


    }

    //    图片上传命名
    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");
        return dateFormat.format(date) + ".jpg";
    }

    private ArrayList<AddNewRecoveryEntity> addNewRecoveryEntityList = new ArrayList<>();

    private void AgentCityListApi() {
        mMProgressDialog.show();
        EasyHttp.post(Constants.AGENTCITYLIST)
                .baseUrl(Constants.APP_API_BASE2)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onSuccess(String s) {
                        MyLog.d("yang", "s==" + s);
                        mMProgressDialog.dismiss();
                        String data = PhoneUtils.checkResponseFlag2(ApplyMerchantActivity.this, s, TAG);
                        if (data != null && !data.equals("[]")) {
                            addNewRecoveryEntityList = new Gson().fromJson(data, new TypeToken<ArrayList<AddNewRecoveryEntity>>() {
                            }.getType());
                            showPickerView(addNewRecoveryEntityList);
                        }
                    }
                });

    }

    private ArrayList<AddNewRecoveryEntity> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<AddNewRecoveryEntity.SubBeanX>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<AddNewRecoveryEntity.SubBeanX.SubBean>>> options3Items = new ArrayList<>();


    private void showPickerView(ArrayList<AddNewRecoveryEntity> jsonBean) {// 弹出选择器
        options1Items = jsonBean;
        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<AddNewRecoveryEntity.SubBeanX> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<AddNewRecoveryEntity.SubBeanX.SubBean>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）
            if (jsonBean.get(i).getSub() != null && jsonBean.get(i).getSub().size() > 0) {
                for (int c = 0; c < jsonBean.get(i).getSub().size(); c++) {//遍历该省份的所有城市
                    String CityName = jsonBean.get(i).getSub().get(c).getName();
                    int CityId = jsonBean.get(i).getSub().get(c).getId();
                    CityList.add(new AddNewRecoveryEntity.SubBeanX(CityId, CityName));//添加城市


                    ArrayList<AddNewRecoveryEntity.SubBeanX.SubBean> City_AreaList = new ArrayList<>();//该城市的所有地区列表
                    //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                    if (jsonBean.get(i).getSub().get(c) != null) {
                        if (jsonBean.get(i).getSub().get(c).getSub() != null && jsonBean.get(i).getSub().get(c).getSub().size() > 0) {
                            City_AreaList.addAll(jsonBean.get(i).getSub().get(c).getSub());

                        } else {
                            City_AreaList.add(new AddNewRecoveryEntity.SubBeanX.SubBean(0, ""));
                        }
                    } else {
                        City_AreaList.add(new AddNewRecoveryEntity.SubBeanX.SubBean(0, ""));
                    }
                    Province_AreaList.add(City_AreaList);//添加该省所有地区数据

                }
            } else {
                CityList.add(new AddNewRecoveryEntity.SubBeanX(0, ""));//添加城市
                ArrayList<AddNewRecoveryEntity.SubBeanX.SubBean> City_AreaList2 = new ArrayList<>();//该城市的所有地区列表
                City_AreaList2.add(new AddNewRecoveryEntity.SubBeanX.SubBean(0, ""));
                Province_AreaList.add(City_AreaList2);//添加该省所有地区数据
            }


            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }


    }

    private String address;
    private int cityId = 0;

    private void showPicker(final int selectLocation) {
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                switch (selectLocation) {
                    case 1:
                        address = options1Items.get(options1).getPickerViewText();
                        cityId = options1Items.get(options1).getId();
                        break;
                    case 2:
                        address = options1Items.get(options1).getPickerViewText() + options2Items.get(options1).get(options2).getPickerViewText();
                        cityId = options2Items.get(options1).get(options2).getId();
                        if (cityId == 0) {
                            cityId = options1Items.get(options1).getId();
                        }
                        break;
                    case 3:
                        address = options1Items.get(options1).getPickerViewText() + options2Items.get(options1).get(options2).getPickerViewText() + options3Items.get(options1).get(options2).get(options3).getPickerViewText();
                        cityId = options3Items.get(options1).get(options2).get(options3).getId();
                        if (cityId == 0) {
                            cityId = options2Items.get(options1).get(options2).getId();
                            if (cityId == 0) {
                                cityId = options1Items.get(options1).getId();
                            }
                        }
                        break;
                }
                tvLocation.setText(address);

                MyLog.d("yang" + "cityId==" + cityId);
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();
        switch (selectLocation) {
            case 1:
                pvOptions.setPicker(options1Items);
                break;
            case 2:
                pvOptions.setPicker(options1Items, options2Items);
                break;
            case 3:
                pvOptions.setPicker(options1Items, options2Items, options3Items);
                break;
        }
        pvOptions.show();
    }
}
